import logging
from may import tools, may_path
import os

log = logging.getLogger(__name__)

default_config_file = ["may.conf", "may.toml", "may.yaml"]

default_config = {
    "log": {
        "logpath": "/var/log/may/may.log"
    },
    "listen": {
        "interface": "127.0.0.1",
        "port": 11892
    },
    "servers": {
        "module": "yaml_file",
        "filepath": "/etc/may/servers.yaml",
    },
    "ssh_conn_pool": {
        "default_port": 22,
        "lazy_load": True,
        "min_num_per_server": 0,
        "max_num_per_server": 3,
        "connect_timeout": 15
    },
    "pid_file": may_path + "may.pid"
}


class MayConfig(dict):
    def _load_dir_config(self, dirpath):
        if os.path.exists(dirpath):
            for filename in default_config_file:
                self._load_file_config(dirpath + filename)

    def _load_file_config(self, filepath: str):
        if filepath.endswith("toml"):
            config = tools.load_toml(filepath)
        elif filepath.endswith("yaml"):
            config = tools.load_yaml(filepath)
        else:
            try:
                config = tools.load_toml(filepath)
            except ValueError:
                config = tools.load_yaml(filepath)
        self._update_config(config)

    def _update_config(self, config):
        tools.recursive_update(self, config)

    def __init__(self, filepath: str = "", config: dict = {}):
        """
        may config
        配置位置优先级由低到高分别是
        1. 本模块的default_config，全局默认配置
        2. /etc/may/may.conf  /etc/may/may.toml  /etc/may/may.yaml
        3. ~/.may/may.conf  ~/.may/may.toml  ~/.may/may.yaml
        4. 执行时带的--config/-c参数，指定特定配置文件
        5. config_dict，用于时测试带测试参数方便
        """
        super().__init__()

        # 加载默认配置
        self.update(default_config)

        # 加载/etc/may目录的配置文件
        self._load_dir_config("/etc/may/")

        # 加载用户配置 ~/.may目录的配置文件
        self._load_dir_config("~/.may/")

        # 加载执行时指定的配置文件
        if filepath:
            self._load_file_config(filepath)

        # 加载执行时指定的配置
        self._update_config(config)
